package org.crazyit.cloud.fallback;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;

/**
 * 回退测试类
 * @author 杨恩雄
 *
 */
public class FallbackTest {

	public static void main(String[] args) {
		// 断路器被强制打开
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.circuitBreaker.forceOpen", "true");
		FallbackCommand c = new FallbackCommand();
		c.execute();
		// 创建第二个命令，断路器关闭
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.circuitBreaker.forceOpen", "false");
		FallbackCommand c2 = new FallbackCommand();
		c2.execute();
	}

	static class FallbackCommand extends HystrixCommand<String> {
		public FallbackCommand() {
			super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
		}

		/**
		 * 断路器被强制打开，该方法不会执行
		 */
		protected String run() throws Exception {
			System.out.println("命令执行");
			return "";
		}

		/**
		 * 回退方法，断路器打开后会执行回退
		 */
		protected String getFallback() {
			System.out.println("执行回退方法");
			return "fallback";
		}
	}
}
